<?php

namespace app\utils;

use yii\helpers\ArrayHelper;
use yii\httpclient\Client;
use yii\web\ForbiddenHttpException;
use yii\web\HttpException;
use yii\web\UnauthorizedHttpException;

class HttpUtil {

    const METHOD_POST = "post";
    const METHOD_GET = "get";

    const FORMAT_JSON = 'json';
    const FORMAT_XML = 'xml';
    const FORMAT_URLENCODED = 'urlencoded';
    const FORMAT_RAW_URLENCODED = 'raw-urlencoded';

    /**
     * 发送HTTP请求获取数据
     * @param string $url 远程服务器地址
     * @param string $method 请求方式
     * @param array $data 请求数据
     * @param string $format 请求格式
     * @param array $headers 请求头
     * @param array $options 可选头
     * @return array 返回数据
     * @throws HttpException
     */
    public static function request($url,$method,array $data,$format,$headers=[],$options=[]){
        $options = ArrayHelper::merge($options,[CURLOPT_SSL_VERIFYPEER=>false,CURLOPT_SSL_VERIFYHOST=>false,CURLOPT_TIMEOUT=>30]);
        if($method == self::METHOD_GET){
            return self::get($url,$data,$format,$headers,$options);
        }else{
            return self::post($url,$data,$format,$headers,$options);
        }
    }

    protected static function post($url,$data,$format,$headers=[],$options=[]){
        $client = new Client([
            //设置采用curl来发送
            'transport' => 'yii\httpclient\CurlTransport',
        ]);
        $response = $client->post($url, $data, $headers, $options)
            ->setFormat($format)
            ->send();

        if($response->getStatusCode() == '401'){
            throw new UnauthorizedHttpException(\Yii::t("app","未授权的请求"));
        }else if($response->getStatusCode() == "403"){
            throw new ForbiddenHttpException(\Yii::t('app', "权限不足,请求被拒绝"));
        }else if($response->getStatusCode() != "200"){
            throw new HttpException(\Yii::t("app","远程服务器请求失败"));
        }

        return $response->getData();
    }

    protected static function get($url,$data,$format,$headers=[],$options=[]){
        $client = new Client([
            //设置采用curl来发送
            'transport' => 'yii\httpclient\CurlTransport',
        ]);
        $response = $client->get($url, $data, $headers, $options)->send();
        if($response->getStatusCode() == '401'){
            throw new UnauthorizedHttpException(\Yii::t("app","未授权的请求"));
        }else if($response->getStatusCode() == "403"){
            throw new ForbiddenHttpException(\Yii::t('app', "权限不足,请求被拒绝"));
        }else if($response->getStatusCode() != "200"){
            throw new HttpException(\Yii::t("app","远程服务器请求失败"));
        }

        return $response->setFormat($format)->getData();
    }
}